package com.itzxx.huazhun.ui.record.valuation

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.github.aachartmodel.aainfographics.aachartcreator.AASeriesElement
import com.itzxx.huazhun.data.dao.ProbeRecordEntity
import com.itzxx.huazhun.data.model.ComplianceResult
import com.itzxx.huazhun.data.model.RecordChildBean
import com.itzxx.huazhun.data.model.RecordCurveAdminDataBean
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.utils.DateUtil
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.databind.IntObservableField
import com.itzxx.library_base_ktx.callback.databind.StringObservableField
import com.itzxx.library_base_ktx.callback.livedata.event.EventLiveData
import com.itzxx.library_base_ktx.ext.request
import com.itzxx.library_base_ktx.state.ListDataUiState
import java.time.LocalTime

class RecordValuationLocalViewModel : BaseViewModel() {
    //列表数据刷新
    val listDataUiStateLiveData = EventLiveData<ListDataUiState<RecordChildBean>>()

    //灭菌温度
    val sterilizationTemperatureObservableField = StringObservableField("134")

    //消毒温度
    val cleanTemperatureObservableField = StringObservableField("90")

    //真空时间
    val vacuumLeakageObservableField = StringObservableField("600")


    var currentCheckSceneTypeIdObservableField = IntObservableField(0)

    val complianceResultLiveData = EventLiveData<ComplianceResult>()
    val noComplianceResultLiveData = EventLiveData<String>()

    var ids = arrayListOf<Int>()

    //曲线时间
    var queryCurveTimeArray = emptyList<String>()

    //曲线数据
    val queryCurveDataMap = mutableMapOf<Int, RecordCurveAdminDataBean>()

    //返回绘制曲线
    val curveDataCategoriesLiveData = MutableLiveData<ArrayList<String>>()

    //返回绘制内容
    val curveDataLiveData = MutableLiveData<ArrayList<AASeriesElement>>()

    val MAX_DRAW_NUM = 200

    @SuppressLint("SimpleDateFormat")
    fun getCurveListData(ids: ArrayList<Int>) {
        request({
            HttpRequestCoroutine.getLocalRecordCurveList(ids)
        }, {
            val queryCurveTimeList = arrayListOf<String>()
            val timeList = arrayListOf<Long>()
            val curvePointList = arrayListOf<HashMap<Long, ProbeRecordEntity>>()
            it.forEach { item ->
                //开始结束
                timeList.add(item.recordStartTime.toLong())
                //开始结束
                timeList.add(item.recordStartTime.toLong() + item.recordNum)
                val simgleProbeRecordMap = hashMapOf<Long, ProbeRecordEntity>()
                for (index in item.probeSamplingRecordInfoList.indices) {
                    simgleProbeRecordMap[item.recordStartTime.toLong() + index] = item.probeSamplingRecordInfoList[index]
                }
                curvePointList.add(simgleProbeRecordMap)
            }
            //曲线开始
            val startTime = timeList.min()
            //曲线结束
            val endTime = timeList.max()
            val stepNum = if ((endTime - startTime) > MAX_DRAW_NUM) {
                (endTime - startTime) / MAX_DRAW_NUM
            } else {
                1
            }
            //x轴
            val tempCurveTimeList = mutableListOf<String>()
            for (i in 0 until  (endTime - startTime) step stepNum) {
                if ((i % stepNum).toInt() != 0) {
                    continue
                }
                tempCurveTimeList.add(DateUtil.formatHMSTime(("${startTime + i}000").toLong()))
            }
            //x轴排序处理
            val sortTempCurveTimeList= tempCurveTimeList.sortedBy { time ->
                LocalTime.parse(time)
            }
            sortTempCurveTimeList.forEach {time->
                queryCurveTimeList.add(LocalTime.parse(time).toString())
            }

            //具体点数据
            val arrayType = arrayListOf<AASeriesElement>()
            curvePointList.forEach { curveItem->
                val arrayPointTempList = arrayListOf<Array<Any>>()
                val arrayPointAirPressureList = arrayListOf<Array<Any>>()
                for (i in 0 until  (endTime - startTime) step stepNum) {
                    if ((i % stepNum).toInt() != 0) {
                        continue
                    }
                    //x轴
                    curveItem[startTime + i]?.run {
                        if (isExistTemp()) {
                            arrayPointTempList.add( arrayOf(
                                DateUtil.formatHMSTime(("${startTime + i}000").toLong()),
                               temperature
                            ))
                        }

                        if (isExistAirPressure()) {
                            arrayPointAirPressureList.add( arrayOf(
                                DateUtil.formatHMSTime(("${startTime + i}000").toLong()),
                                airPressure
                            ))
                        }
                    }
                }
                if (arrayPointTempList.isNotEmpty()){
                    arrayType.add(
                        AASeriesElement()
                            .name("温度")
                            .data(arrayPointTempList.toArray())
                    )
                }
                if (arrayPointAirPressureList.isNotEmpty()){
                    arrayType.add(
                        AASeriesElement()
                            .name("气压")
                            .data(arrayPointAirPressureList.toArray())
                    )
                }

            }
            //绘制标题

            curveDataCategoriesLiveData.postValue(queryCurveTimeList)
            curveDataLiveData.postValue(arrayType)
        }, {

        })
    }

    fun getLocalData(sceneType: Int, ids: ArrayList<Int>) {
        this.currentCheckSceneTypeIdObservableField.set(sceneType)
        this.ids = ids
        var tempTemperature = 0.0
        when (sceneType) {
            2 -> {
                tempTemperature = sterilizationTemperatureObservableField.get().toDouble()
            }

            7 -> {
                tempTemperature = cleanTemperatureObservableField.get().toDouble()
            }

            else -> {
                tempTemperature = vacuumLeakageObservableField.get().toDouble()
            }
        }

        request({
            HttpRequestCoroutine.onValuationResult(sceneType, ids, tempTemperature)
        }, {
            complianceResultLiveData.postValue(it.complianceResult)
            noComplianceResultLiveData.postValue(it.noComplianceResult)
        }, {

        }, isShowDialog = true)
    }

    fun onValuation() {
        if (currentCheckSceneTypeIdObservableField.get() == 2) {
            if (TextUtils.isEmpty(sterilizationTemperatureObservableField.get())) {
                toast("请输入灭菌温度！")
                return
            }
        } else if (currentCheckSceneTypeIdObservableField.get() == 7) {
            if (TextUtils.isEmpty(cleanTemperatureObservableField.get())) {
                toast("请输入消毒温度！")
                return
            }
        } else {
            if (TextUtils.isEmpty(vacuumLeakageObservableField.get())) {
                toast("请输入真空时间！")
                return
            } else if (vacuumLeakageObservableField.get().toInt() < 60) {
                toast("真空时间不得小于1分钟")
                return
            }
        }
        getLocalData(currentCheckSceneTypeIdObservableField.get(), ids)
    }
}